package com.meetflow.conference.service.impl;

import com.meetflow.common.core.domain.entity.SysUser;
import com.meetflow.common.utils.DateUtils;
import com.meetflow.common.utils.SecurityUtils;
import com.meetflow.conference.domain.MeetFlowAction;
import com.meetflow.conference.domain.MeetRecord;
import com.meetflow.conference.mapper.MeetFlowActionMapper;
import com.meetflow.conference.mapper.MeetRecordMapper;
import com.meetflow.conference.service.IMeetRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * 我的申请Service业务层处理
 *
 * @author duanjj
 * @date 2024-07-12
 */
@Service
public class MeetRecordServiceImpl implements IMeetRecordService {

    @Autowired
    private MeetRecordMapper meetRecordMapper;

    @Autowired
    private MeetFlowActionMapper meetFlowActionMapper;

    /**
     * 查询我的申请
     *
     * @param id 我的申请主键
     * @return 我的申请
     */
    @Override
    public MeetRecord selectMeetRecordById(Long id, String taskStatus) {
        MeetRecord meetRecord = meetRecordMapper.selectMeetRecordById(id, taskStatus);

//        String[] strArray = meetRecord.getNodeUserNos().split(",");
//        int[] intArray = Arrays.stream(strArray)
//                .mapToInt(Integer::parseInt)
//                .toArray();
//        meetRecord.setApproversNos(intArray);
        return meetRecord;
    }


    @Override
    public Map<String, Long> getToDoNum(Long id, String userLevel){
        return meetRecordMapper.getToDoNum(id, userLevel);
    }

    @Override
    public MeetRecord selectMeetRecordDetailById(Long id){
        MeetRecord meetRecord = meetRecordMapper.selectMeetRecordDetailById(id);
        if (StringUtils.isNotEmpty(meetRecord.getNodeUserNos())) {
            String[] strArray = meetRecord.getNodeUserNos().split(",");
            int[] intArray = Arrays.stream(strArray)
                    .mapToInt(Integer::parseInt)
                    .toArray();
            meetRecord.setApproversNos(intArray);
        }
        List<MeetFlowAction> list =meetFlowActionMapper.selectMeetFlowActionListByRecordId(id);
        meetRecord.setFlowList(list);
        return meetRecord;
    }

    @Override
    public int rejectMeetRecord(MeetRecord meetRecord){
        if (StringUtils.isNotEmpty(meetRecord.getProblemLevel()) && Integer.valueOf(meetRecord.getProblemLevel()) - 1 >=0) {
             meetRecordMapper.updateMeetRecordProblemLevel(meetRecord.getId(), String.valueOf(Integer.valueOf(meetRecord.getProblemLevel()) - 1));
        } else {
            return 0;
        }
        MeetFlowAction action = new MeetFlowAction();
        action.setMeetRecordId(meetRecord.getId());
        action.setMeetSimCode(String.valueOf(meetRecord.getMeetSimFirstCode()));
        action.setMeetSimName(meetRecord.getMeetSimFirstName());
        action.setTaskStatus(meetRecord.getTaskStatus());
        action.setMeetStatus(Long.valueOf(3));
        return meetFlowActionMapper.insertMeetFlowAction(action);
    }

    @Override
    public int updateProblemLevelMeetRecord(MeetRecord meetRecord){
        if (StringUtils.isNotEmpty(meetRecord.getProblemLevel()) && Integer.valueOf(meetRecord.getProblemLevel()) + 1 <=4) {
            meetRecordMapper.updateMeetRecordProblemLevel(meetRecord.getId(), String.valueOf(Integer.valueOf(meetRecord.getProblemLevel()) + 1));
        } else {
            return 0;
        }
        MeetFlowAction action = new MeetFlowAction();
        action.setMeetRecordId(meetRecord.getId());
        action.setMeetSimCode(String.valueOf(meetRecord.getMeetSimFirstCode()));
        action.setMeetSimName(meetRecord.getMeetSimFirstName());
        action.setTaskStatus(meetRecord.getTaskStatus());
        action.setMeetStatus(Long.valueOf(2));
        return meetFlowActionMapper.insertMeetFlowAction(action);
    }

    @Override
    public int closeMeetRecord(MeetRecord meetRecord){
        meetRecordMapper.closeMeetRecord(meetRecord.getId());
        MeetFlowAction action = new MeetFlowAction();
        action.setMeetRecordId(meetRecord.getId());
        action.setMeetSimCode(String.valueOf(meetRecord.getMeetSimFirstCode()));
        action.setMeetSimName(meetRecord.getMeetSimFirstName());
        action.setTaskStatus(meetRecord.getTaskStatus());
        action.setMeetSimTime(new Date());
        action.setMeetStatus(Long.valueOf(3));
        action.setMeetAction("撤回申请");
        return meetFlowActionMapper.insertMeetFlowAction(action);
    }

    @Override
    public int acceptanceMeetRecord(MeetRecord meetRecord){
        return meetRecordMapper.updateMeetRecord(meetRecord);
    }

    @Override
    public List<Long> getAllRecordIds(MeetRecord meetRecord){
        return meetRecordMapper.getAllRecordIds(meetRecord);
    }

    /**
     * 查询我的申请列表
     *
     * @param meetRecord 我的申请
     * @return 我的申请
     */
    @Override
    public List<MeetRecord> selectMeetRecordList(MeetRecord meetRecord) {
        return meetRecordMapper.selectMeetRecordList(meetRecord);
    }
    @Override
    public List<MeetRecord> selectExportMeetRecordList(MeetRecord meetRecord) {
        return meetRecordMapper.selectExportMeetRecordList(meetRecord);
    }
    @Override
    public List<MeetRecord> selectMeetRecordListByParam(MeetRecord meetRecord) {
        return meetRecordMapper.selectMeetRecordListByParam(meetRecord);
    }

    /**
     * 新增我的申请
     *
     * @param meetRecord 我的申请
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMeetRecord(MeetRecord meetRecord) {
        meetRecord.setTaskStatus(meetRecord.getProblemLevel());
        meetRecord.setCheckStatus("1");
        meetRecord.setAutoUpgradationTime(meetRecord.getApplicantTime());
        meetRecordMapper.insertMeetRecord(meetRecord);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        MeetFlowAction action = new MeetFlowAction();
        action.setMeetRecordId(meetRecord.getId());
        action.setMeetSimCode(String.valueOf(user.getUserId()));
        action.setMeetSimName(user.getNickName());
        action.setMeetSimTime(new Date());
        action.setMeetAction("提交申请");
        action.setTaskStatus(meetRecord.getTaskStatus());
        action.setMeetStatus(0l);
        return meetFlowActionMapper.insertMeetFlowAction(action);
    }

    private static List<MeetFlowAction> getInsertMeetFlowActions(MeetRecord meetRecord) {
        List<MeetFlowAction> list = new ArrayList<MeetFlowAction>();
        for (int i = 0; i < meetRecord.getApproversNos().length; i++) {
            MeetFlowAction meetFlowAction = new MeetFlowAction();
            meetFlowAction.setMeetSimCode(String.valueOf(meetRecord.getApproversNos()[i]));
            meetFlowAction.setMeetRecordId(meetRecord.getId());
            meetFlowAction.setTaskStatus("1");
            list.add(meetFlowAction);
        }
        return list;
    }

    @Override
    @Transactional
    public int stagingApplyTask(MeetRecord meetRecord) {
        meetRecord.setTaskStatus("0");
        meetRecord.setCheckStatus("0");
        if (meetRecord.getId() != null) {
            return meetRecordMapper.updateMeetRecord(meetRecord);//getStagingMeetFlowActions(meetRecord);
        } else {
            List<MeetFlowAction> list = new ArrayList<MeetFlowAction>();
            MeetFlowAction action = new MeetFlowAction();
//            List<MeetFlowAction> list = getStagingInsertMeetFlowActions(meetRecord);
//            return meetFlowActionMapper.batchInsertMeetFlowAction(list);
            return meetRecordMapper.insertMeetRecord(meetRecord);
        }
    }

    private static List<MeetFlowAction> getStagingInsertMeetFlowActions(MeetRecord meetRecord) {
        List<MeetFlowAction> list = new ArrayList<MeetFlowAction>();
        for (int i = 0; i < meetRecord.getApproversNos().length; i++) {
            MeetFlowAction meetFlowAction = new MeetFlowAction();
            meetFlowAction.setMeetSimCode(String.valueOf(meetRecord.getApproversNos()[i]));
            meetFlowAction.setMeetRecordId(meetRecord.getId());
            meetFlowAction.setTaskStatus("0");
            list.add(meetFlowAction);
        }
        return list;
    }

    private Integer getStagingMeetFlowActions(MeetRecord meetRecord) {
        int k = 0;
        for (int i = 0; i < meetRecord.getApproversNos().length; i++) {
            MeetFlowAction meetFlowAction = new MeetFlowAction();
            meetFlowAction.setMeetSimCode(String.valueOf(meetRecord.getApproversNos()[i]));
            meetFlowAction.setMeetRecordId(meetRecord.getId());
            if (StringUtils.isNotBlank(meetRecord.getFlowIds())) {
                String[] idsArray = meetRecord.getFlowIds().split(",");
                meetFlowAction.setId(Long.valueOf(idsArray[i]));
            }
            meetFlowAction.setTaskStatus(meetRecord.getTaskStatus());
            k = meetFlowActionMapper.updateMeetFlowAction(meetFlowAction);
        }
        return k;
    }


    private Integer getMeetFlowActions(MeetRecord meetRecord) {
        int k = 0;
        for (int i = 0; i < meetRecord.getApproversNos().length; i++) {
            MeetFlowAction meetFlowAction = new MeetFlowAction();
            meetFlowAction.setMeetSimCode(String.valueOf(meetRecord.getApproversNos()[i]));
            meetFlowAction.setMeetRecordId(meetRecord.getId());
            meetFlowAction.setTaskStatus(meetRecord.getTaskStatus());
            if (StringUtils.isNotBlank(meetRecord.getFlowIds())) {
                String[] idsArray = meetRecord.getFlowIds().split(",");
                meetFlowAction.setId(Long.valueOf(idsArray[i]));
            }
            k = meetFlowActionMapper.updateMeetFlowAction(meetFlowAction);
        }
        return k;
    }

    /**
     * 修改我的申请
     *
     * @param meetRecord 我的申请
     * @return 结果
     */
    @Override
    @Transactional
    public int updateMeetRecord(MeetRecord meetRecord) {
        //选择的问题层级 与 审批状态接口关联
        meetRecord.setTaskStatus(meetRecord.getProblemLevel());
        meetRecord.setAutoUpgradationTime(meetRecord.getApplicantTime());
        meetRecord.setCheckStatus("1");
        meetRecord.setUpdateTime(DateUtils.getNowDate());
        meetRecordMapper.updateMeetRecord(meetRecord);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        MeetFlowAction action = new MeetFlowAction();
        action.setMeetRecordId(meetRecord.getId());
        action.setMeetSimCode(String.valueOf(user.getUserId()));
        action.setMeetSimName(user.getNickName());
        action.setMeetSimTime(new Date());
        action.setMeetAction("提交申请");
        action.setTaskStatus(meetRecord.getTaskStatus());
        action.setMeetStatus(0l);
        return meetFlowActionMapper.insertMeetFlowAction(action);
    }

    /**
     * 批量删除我的申请
     *
     * @param ids 需要删除的我的申请主键
     * @return 结果
     */
    @Override
    public int deleteMeetRecordByIds(Long[] ids) {
        return meetRecordMapper.deleteMeetRecordByIds(ids);
    }

    /**
     * 删除我的申请信息
     *
     * @param id 我的申请主键
     * @return 结果
     */
    @Override
    public int deleteMeetRecordById(Long id) {
        return meetRecordMapper.deleteMeetRecordById(id);
    }

    /**
     * 根据当前时间 获取需自动升级的工单
     */
    @Override
    public void autoUpgradeProblemLevelByUpgradationTime(MeetRecord meetRecord) {
        List<MeetRecord> meetRecordList = meetRecordMapper.selectMeetRecordList(meetRecord);
        MeetRecord tempMeetRecord = null;
        for (MeetRecord nowMeetRecord : meetRecordList) {
            LocalDateTime autoUpgradationTime = nowMeetRecord.getAutoUpgradationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            // 检查是否超过24小时
            if (autoUpgradationTime.isBefore(LocalDateTime.now().minus(1, ChronoUnit.DAYS))) {
                LocalDateTime newAutoUpgradationTime = calculateNextUpgradeTime(autoUpgradationTime);

                tempMeetRecord = new MeetRecord();
                tempMeetRecord.setAutoUpgradation("1");
                tempMeetRecord.setProblemLevel(String.valueOf((Integer.parseInt(nowMeetRecord.getProblemLevel()) + 1)));
                tempMeetRecord.setTaskStatus(String.valueOf((Integer.parseInt(nowMeetRecord.getTaskStatus()) + 1)));
                tempMeetRecord.setAutoUpgradationTime(DateUtils.toDate(newAutoUpgradationTime));
                tempMeetRecord.setId(nowMeetRecord.getId());
                //再最高层级时不在操作  最高操作为4级
                if (!nowMeetRecord.getTaskStatus().equals("4")) {
                    meetRecordMapper.updateMeetRecord(tempMeetRecord);
                }
            }
        }
    }


    private LocalDateTime calculateNextUpgradeTime(LocalDateTime lastUpgradeTime) {
        LocalDateTime nextUpgradeTime = lastUpgradeTime.plusDays(1);
        // 如果加上一天后的时间仍然小于当前时间，则设置为当前时间
        if (nextUpgradeTime.isBefore(LocalDateTime.now())) {
            nextUpgradeTime = LocalDateTime.now();
        } else {
            // 跳过周六周日
            while (nextUpgradeTime.getDayOfWeek() == DayOfWeek.SATURDAY || nextUpgradeTime.getDayOfWeek() == DayOfWeek.SUNDAY) {
                nextUpgradeTime = nextUpgradeTime.plusDays(1);
            }
        }
        return nextUpgradeTime;
    }

}
